package com.luckylo.activemq.local;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQObjectMessage;

import javax.jms.*;

/**
 * 消息队列之消费者
 *
 * @user: luckylo
 * @date: 2018-1-18
 */
public class Consumer implements MessageListener {

    private static Session session;

    static {
        try {
            init();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    private static void init() throws JMSException {
        // 获取连接工厂
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
        // 如果此处不信任所有包的话,可能会导致反序列化失败!!!!
        factory.setTrustAllPackages(true);

        // 获取连接
        Connection connection = factory.createConnection();

        // 启动.才能获取session
        connection.start();

        // 参数未搞明白意思
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    }


    public static void main(String[] args) throws JMSException {
        Queue queue = session.createQueue("queue");

//        Topic topic = session.createTopic("topic");
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(new Consumer());
    }

    @Override
    public void onMessage(Message message) {
        ActiveMQObjectMessage mqObjectMessage = (ActiveMQObjectMessage) message;

        try {
            com.luckylo.activemq.bean.Message object = (com.luckylo.activemq.bean.Message) mqObjectMessage.getObject();

            System.out.println("queue 方式收到消息 " + object);

        } catch (JMSException e) {
            e.printStackTrace();
        }


//        // topic 模式的  纯文本消息
//        TextMessage textMessage = (TextMessage) message;
//        try {
//            System.out.println("topic 方式收到消息 " + textMessage.getText());
//        } catch (JMSException e) {
//            e.printStackTrace();
//        }
    }
}
